Ext.define('Gigi.controller.Groups', {
	extend : 'Ext.app.Controller',

	views : ['group.Tree', 'group.Tab', 'group.Edit', 'group.AddUserList'],
	stores : ['Groups', 'GroupUsers', 'Users', 'Authorities',
			'GroupAuthorities'],
	models : ['Group', 'User', 'Authority'],

	/**
	 * 初始化按钮事件函数
	 */
	init : function() {
		this.control({
					'#add' : {
						click : this.onAddClick
					},
					'#delete' : {
						click : this.onDeleteClick
					},
					'#update' : {
						click : this.onUpdateClick
					},
					'groupedit button[action=save]' : {
						click : this.onEditSaveClick
					},
					'#addUser' : {
						click : this.onAddGroupUsersClick
					},
					'#deleteUser' : {
						click : this.onDeleteGroupUsersClick
					},
					'adduserwin button[action=save]' : {
						click : this.onAddGroupUsersSaveClick
					},
					'#saveAuthorities' : {
						click : this.onSaveAuthoritiesClick
					}
				});
	},

	/**
	 * 用户组新增按钮单击处理函数。
	 * 
	 * @param {}
	 *            button
	 */
	onAddClick : function(button) {
		var tree = button.up('grouptree'), selModel = tree.getSelectionModel();
		var win = Ext.widget('groupedit', {
					title : '新增用户组'
				});
		var form = win.down('form');
		var group = Ext.create('Gigi.model.Group');
		if (selModel.getCount() != 0) {
			group.set('parent_id', selModel.getSelection()[0].get('id'));
		} else {
			group.set('parent_id', 0);
		}
		form.loadRecord(group);
	},

	/**
	 * 用户组删除按钮单击处理函数。
	 * 
	 * @param {}
	 *            button
	 */
	onDeleteClick : function(button) {
		var tree = button.up('grouptree'), selModel = tree.getSelectionModel();
		if (selModel.getCount() == 0) {
			Ext.Msg.show({
						title : '删除用户组',
						msg : '请选择一条记录',
						icon : Ext.MessageBox.ERROR,
						buttons : Ext.MessageBox.OK
					});
		} else {
			var selectNode = selModel.getSelection()[0];
			if (selectNode.hasChildNodes()) {
				Ext.Msg.show({
							title : '删除用户组',
							msg : '当前用户组下已经有子用户组，不允许删除！',
							icon : Ext.MessageBox.ERROR,
							buttons : Ext.MessageBox.OK
						});
			} else {
				Ext.Msg.show({
							title : '删除用户组',
							msg : '您确认删除吗？',
							icon : Ext.MessageBox.QUESTION,
							fn : function(btn) {
								if (btn == "ok") {
									selectNode.destroy({
												success : function() {
													Ext.MessageBox.alert(
															'删除用户组', '删除成功！');
													selectNode.remove(true);
												},
												failure : function(response,
														opts) {
													Ext.MessageBox
															.alert(
																	'删除用户组',
																	response.responseText);
												}
											});
								}
							},
							buttons : Ext.MessageBox.OKCANCEL
						});
			}
		}
	},

	/**
	 * 用户组修改按钮单击处理函数。
	 * 
	 * @param {}
	 *            button
	 */
	onUpdateClick : function(button) {
		var grid = button.up('grouptree'), selModel = grid.getSelectionModel();
		if (selModel.getCount() != 1) {
			Ext.Msg.show({
						title : '修改用户组',
						msg : '请选择一条记录',
						icon : Ext.MessageBox.ERROR,
						buttons : Ext.MessageBox.OK
					});
		} else {
			var win = Ext.widget('groupedit', {
						title : '修改用户组',
						actionType : 'update'
					});
			var form = win.down('form');
			var group = Ext.ModelManager.getModel('Gigi.model.Group');
			group.load(selModel.getSelection()[0].get('id'), {
						success : function(group) {
							form.loadRecord(group);
						}
					});

		}
	},

	/**
	 * 用户组编辑（新增、修改）弹出页面的保存按钮处理函数。
	 * 
	 * @param {}
	 *            button
	 */
	onEditSaveClick : function(button) {
		var win = button.up('window'), form = win.down('form').getForm(), grouptree = Ext.ComponentQuery
				.query('grouptree')[0], selModel = grouptree
				.getSelectionModel();
		if (form.isValid()) {
			var group = Ext.create('Gigi.model.Group', form.getValues());
			var operation = win.actionType;
			if (operation == 'create') {
				group.phantom = true;
			} else {
				group.phantom = false;
			}
			group.save({
						success : function(record, operation) {
							Ext.MessageBox.alert('保存用户组', '保存成功！');
							win.close();
							grouptree.getStore().load({
										node : selModel.getSelection()[0]
									});
						},
						failure : function(record, operation) {
							Ext.MessageBox.alert('保存用户组', '保存用户失败！');
						}
					});
		};
	},

	/**
	 * 用户组用户管理新增按钮单击处理函数。
	 * 
	 * @param {}
	 *            button
	 */
	onAddGroupUsersClick : function(button) {
		var tree = Ext.ComponentQuery.query('grouptree')[0], selModel = tree
				.getSelectionModel();
		var win = Ext.widget('adduserwin', {
					title : '添加用户',
					groupId : selModel.getSelection()[0].get('id')
				});
		var list = win.down('adduserlist');
	},

	/**
	 * 用户组新增用户弹出页面新增按钮单击处理函数。
	 * 
	 * @param {}
	 *            button
	 */
	onAddGroupUsersSaveClick : function(button) {
		var win = button.up('window'), panel = win.down('panel'), groupusers = Ext.ComponentQuery
				.query('groupusers')[0], gustore = groupusers.getStore(), selModels = Ext.ComponentQuery
				.query('adduserlist')[0].getSelectionModel().getSelection();
		for (index in selModels) {
			selModels[index].phantom = true;
		}
		gustore.insert(0, selModels);
		gustore.sync();
		win.close();
		// gustore.load();
	},

	/**
	 * 用户组删除用户按钮单击处理函数。
	 * 
	 * @param {}
	 *            button
	 */
	onDeleteGroupUsersClick : function(button) {
		var groupusers = Ext.ComponentQuery.query('groupusers')[0], gustore = groupusers
				.getStore(), selModel = groupusers.getSelectionModel();
		if (selModel.getCount() == 0) {
			Ext.Msg.show({
						title : '删除用户组用户',
						msg : '请选择至少一条记录',
						icon : Ext.MessageBox.ERROR,
						buttons : Ext.MessageBox.OK
					});
		} else {
			Ext.Msg.show({
						title : '删除用户组用户',
						msg : '您确认删除吗？',
						icon : Ext.MessageBox.QUESTION,
						fn : function(btn) {
							if (btn == "ok") {
								gustore.remove(selModel.getSelection());
								gustore.sync();
							}
						},
						buttons : Ext.MessageBox.OKCANCEL
					});
		}
	},

	/**
	 * 用户组权限功能，保存修改按钮处理函数。
	 * @param {} button
	 */
	onSaveAuthoritiesClick : function(button) {
		var groupauthorities = Ext.ComponentQuery.query('groupauthorities')[0], selAuthorities = groupauthorities
				.getSelectionModel().getSelection(), groupstore = groupauthorities.groupStore;
		var selAuthMap = {}, oldAuthMap = {}; //选择的和原有的权限code的map。
		var i = 0, len = selAuthorities.length;
		for (; i < len; ++i) {
			selAuthMap[selAuthorities[i].get('code')] = true;
		}
		groupstore.each(function(record) {
					oldAuthMap[record.get('code')] = true;
				});
		var len = groupstore.getCount(), i = len-1;
		for (; i > -1; --i) {
			if (!selAuthMap[groupstore.getAt(i).get('code')]) {
				groupstore.removeAt(i);
			}
		}
		for (var key in selAuthMap) {
			if (!oldAuthMap[key]) {
				var model = Ext.create(Gigi.model.Authority, {code : key});
				model.phantom = true;
				groupstore.insert(groupstore.getCount(), model);
			}
		}
		groupstore.sync();
	}
});